# from new_func.print_log import log
from PyQt5.QtCore import pyqtSignal
from resources.unpack_datas import Unpack_Form
from new_func.tools import Tool
import csv, re
from pathlib import Path
import pandas as pd
from PyQt5.QtWidgets import QFrame


class UnpackWidget(QFrame, Unpack_Form):
    path = ''
    texts = ''

    success = pyqtSignal()
    warn = pyqtSignal()
    error = pyqtSignal()

    def __init__(self, text: str, parent=None):
        super(UnpackWidget, self).__init__(parent=parent)
        # self.unpack_ui = Unpack_Form()
        # self.unpack_ui.setupUi(self)
        self.tool = Tool()
        self.setupUi(self)
        self.setObjectName(text.replace(' ', '-'))

        self.dataDict = {}
        self.signals()
        self.save_path = Path(self.path).parent

    def signals(self):
        """按钮触发"""
        self.btn_get.clicked.connect(lambda: self.csv_path())
        self.excelGetPath.clicked.connect(lambda: self.excel_path())

    def read_log(self):
        if self.path:
            with open(self.path, 'r', encoding='utf-8') as r:
                self.texts = r.read()

    def csv_path(self):
        """csv文件"""
        self.tool.csv_file_path(self.line_filename, self.line_filename)
        self.path = self.tool.path

    def excel_path(self):
        """excel文件"""
        self.tool.excel_file_path(self.excelPath, self.excelPath)
        self.path = self.tool.path

    def remove_excel_file(self):
        """
        :return: 文件路径，如果存在即删除
        """
        xlsx_path = self.save_path / "日志解析数据.xlsx"
        if xlsx_path.is_file():  # 判断这个路径的文件是否存在
            xlsx_path.unlink()  # 如果文件存在，那么删除它

    def remove_csv_file(self):
        csv_path = self.save_path / "日志解析数据.csv"
        if csv_path.is_file():  # 判断这个路径的文件是否存在
            csv_path.unlink()  # 如果文件存在，那么删除它

    def csv_unpack_click(self):
        """csv数据解析按钮"""
        # log.info("\033[0;32m" + '进入CSV' + "\033[0m")
        self.read_log()
        list_dic = []
        file_path = self.line_filename.text()
        arg1 = self.line_data1.text()
        arg2 = self.line_data2.text()
        if file_path and arg1 and arg2:
            # log.info("\033[0;32m" + '执行CSV数据中' + "\033[0m")
            pattern = re.compile(r'(?<=<{}>)([\s\S]*?)(?<=<{}>)'.format(arg1, arg2), re.DOTALL | re.IGNORECASE)
            if pattern:
                matches = pattern.findall(self.texts)
                for values in matches:
                    pattern = re.compile(r'\[(.*)\]\s*(.*)\s+:\s*(.+?)(?=\s|$)')
                    #     # 将数据字符串转换成字典
                    my_dict = {}
                    for line in values.split('\n'):
                        match = pattern.match(line)
                        if match:
                            key = match.group(2).strip()
                            values = match.group(3).strip()
                            my_dict[key] = values
                    list_dic.append(my_dict)
                headers = [key for key in list_dic[0]]
                self.remove_csv_file()
                self.write_csv(headers, list_dic)
                self.success.emit()
                print("csv数据筛选成功")
                # log.info("\033[0;32m" + '执行成功' + "\033[0m")
        else:
            # log.warning("\033[0;32m" + 'CSV解析缺少参数' + "\033[0m")
            self.warn.emit()

    def write_csv(self, headers, values):
        """
        :param path_name:  路径及名称
        :param title: 标题第一格头
        :return: csv file
        delimiter=','：使用逗号作为分隔符。
        quoting=csv.QUOTE_ALL：表示对所有元素都要加上引号，即使元素本身没有逗号也要加上引号。
        这是为了避免在特殊情况下，如元素中包含分隔符或引号时产生语法错误。
        """
        with open(self.save_path / "日志解析数据.csv", 'w', newline='') as file:
            # for header in headers:
            writer = csv.DictWriter(file, fieldnames=headers, delimiter=',', quoting=csv.QUOTE_ALL)
            writer.writeheader()
            for value in values:
                try:
                    writer.writerow(value)
                except ValueError:
                    pass
        print("csv写入完成")
        # log.info("\033[0;32m" + 'csv写入完成' + "\033[0m")

    def excel_unpack_click(self):
        """
        :return: info数据筛选
        excel数据解析按钮
        """
        # log.info("\033[0;32m" + '进入excel' + "\033[0m")
        self.read_log()
        if self.excelPath.text():
            values = re.findall('<.*?>', self.texts)
            orderValues = list(dict.fromkeys(values))
        else:
            # log.warning("\033[0;32m" + 'excel解析缺少参数' + "\033[0m")
            self.warn.emit()
        try:
            for order, num in zip(orderValues, range(len(orderValues) - 1)):
                pattern = r"{}([\s\S]*?){}".format(re.escape(values[num]), re.escape(values[num + 1]))
                datas = re.findall(pattern, self.texts)
                for data in datas:
                    # dataValue = re.findall('(.*])(\w*\s*):\s*(.*)', data)
                    dataValue = re.findall(r'\[(.*)\]\s*(\w*\s*)\s*:\s*([^\s]*)', data)
                    if order not in self.dataDict:
                        self.dataDict[order] = {}
                        self.dataDict[order]['time'] = []

                    for item in dataValue:
                        time, key, value = item[0], item[1].strip(), item[2]
                        if key not in self.dataDict[order]:
                            self.dataDict[order][key] = []
                        self.dataDict[order][key].append(value)
                    self.dataDict[order]['time'].append(time)
            self.remove_excel_file()
            print("excel数据筛选成功")
            # print(self.dataDict)
            self.writer_Excel(self.save_path / "日志解析数据.xlsx")
            # log.info("\033[0;32m" + '写入成功' + "\033[0m")
            self.success.emit()
        except:
            # log.error("\033[0;32m" + 'excel解析错误' + "\033[0m")
            self.error.emit()
            self.dataDict.clear()

    def writer_Excel(self, filePath: str):
        """`
        :param filePath: # 存储路径
        :return:   做数据图
        """
        with pd.ExcelWriter(filePath) as writer:
            for sheet_name, data in self.dataDict.items():
                df = pd.DataFrame(data)
                for column in df.columns:
                    if df[column].dtype == object:  # 检查列的数据类型是否为对象类型
                        try:
                            # 尝试将值转换为浮点数
                            df[column] = df[column].astype(float)
                        except ValueError:
                            # 转换失败，将值保持为字符串
                            df[column] = df[column].astype(str)
                df.to_excel(writer, sheet_name=sheet_name, index=False)
        print("excel写入完成")
        # log.info("\033[0;32m" + 'excel写入完成' + "\033[0m")
